package com.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketUtil {

	/**
	 * 是否端口已经被占用
	 * true被占用 
	 * false没有被占用
	 * @param port
	 * @return
	 */
	public static boolean isUseredPort(int port) {
		try {
			Socket socket = new Socket("localhost",port);
			socket.close();
			return true;
		}
		catch (Exception ex) {
			return false;
		}
	}
	
	/**
	 * 获取请求URL
	 * @param request
	 * @return
	 */
	public static String getRequestIp(Socket socket) {
		return socket.getInetAddress().getHostAddress();
	}
	
	public static Socket connect(final String hostname, int port, int connectionTimeout) {
		return cn.hutool.socket.SocketUtil.connect(hostname, port,connectionTimeout);
	}
 	
	public static void main(String[] args) throws UnknownHostException, IOException {
		
//		System.err.println(isUseredPort(6379));
		Socket socket = new Socket("192.168.0.112",7002);
//		System.err.println(socket);
		
//		Socket socket = new Socket("114.67.77.118",8693);
//		System.err.println(socket);
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String sss=in.readLine();
		while(sss.length()>0) {
			System.err.println(sss);
			sss=in.readLine();
		}
		System.err.println("end");
		socket.close();
	}
}
